package com.huynv.redblue;
import android.media.AudioManager;
import android.media.SoundPool;
import android.media.SoundPool.OnLoadCompleteListener;
import android.media.ToneGenerator;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.util.Log;
import android.view.*;
import android.view.View.OnTouchListener;
import android.os.SystemClock;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.Paint.Style;
import android.graphics.PorterDuff.Mode;
import android.view.View;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;

import 	java.lang.Thread;

import android.widget.RelativeLayout;
import android.widget.TextView;
import android.app.AlertDialog;
import android.app.Dialog;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.net.URLEncoder;

import com.google.ads.*;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.huynv.redblue.R;

import android.content.SharedPreferences;
import android.preference.*;
import android.provider.MediaStore.Images;

public class PlayGame extends Activity {
//private RandomShapeView mDrawingArea;
private gameView myView;
private long oldTime;
private long newTime;
private boolean running=true;
private boolean isStillOk=false;
private Thread thread;
private int totalPoints=0;
private TextView  tv;
private int maxDelay=1000;
private String gameOver="Game Over! ";
private int newHighScore=1;
private String packageName="com.huynv.redblue";
private byte typeOfGameOver=0;//touch slowlly!=1, touch red circle
private String[] gameOverAlert=new String[] {"you are too slow!","don't touch if the text not same as the text color!"};
private AlertDialog.Builder alertDialogBuilder;
private AlertDialog alertDialog;
private int countReadyGame=3;
private String startGameGuide="Touch anywhere!";

private String MY_AD_UNIT_ID="ca-app-pub-6575239088642506/1558548874";//"a153131675c8136";
private final int TONE_TYPE = ToneGenerator.TONE_DTMF_5;
private final int STREAM = AudioManager.STREAM_MUSIC;
private final int DOT_TIME = 3;
private AudioManager audio;
private ToneGenerator generator;
private SoundPool soundPool;
private int soundIDTrue;
private int soundIDOver;
private View _rootView;
private AdView adView;
private Context context;
private File currentFile=null;
@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		context=this.context;
		setContentView(R.layout.active_game_play);
		_rootView=(View) findViewById(R.id.LinearLayout1);
		soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
	    soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
	      @Override
	      public void onLoadComplete(SoundPool soundPool, int sampleId,
	          int status) {
	    	  //loaded = true;
	      }
	    });
	    soundIDTrue = soundPool.load(this, R.raw.ftrue, 1);
	    soundIDOver = soundPool.load(this, R.raw.wrong, 1);
//		audio = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
//	    generator = new ToneGenerator(STREAM,audio.getStreamMaxVolume(STREAM));
	    
		oldTime=System.currentTimeMillis();
		newTime=oldTime;
		totalPoints=0;
		tv=(TextView) findViewById(R.id.points);
		running=true;
		isStillOk=false;		
		newHighScore=getHightSorce();
		if (newHighScore==0) saveHightScore();
		tv.setText(startGameGuide);		
		//if (newHighScore==null) newHighScore=0;
		myView = (gameView)findViewById(R.id.custView);
		
		myView.setOnTouchListener(new OnTouchListener() {
	        @Override
	        public boolean onTouch(View v, MotionEvent event) {
	        	//if (!running) 
	        	//{
	        		//tv.setText("Scores: 0");
	        		//restartGame();
	        		//return false;	        		
	        	//}
	        	if (myView.getIsGameOver()==true)
	        	{
	        		showGameOver();
	        		return false;
	        	}
	        	oldTime=myView.getOldTime();
	        	newTime=System.currentTimeMillis();
	        	long diff=(newTime-oldTime);
	        	//Log.e("color",String.valueOf(myView.getCurrentColor()));
	        	//Log.e("time",String.valueOf(diff));
	        	if (myView.getCurrentColor()==1 && diff<=maxDelay){
	        		//Log.e("Cham vao mau do", "Cham vao mau do");
	        		running=false;
	        		oldTime=System.currentTimeMillis();
	        		newTime=oldTime;
	        		myView.setGameOver(gameOver+"Your EQ scores are "+String.valueOf(totalPoints)+" points");
	        		myView.setLabelText(gameOver+"Your EQ scores are "+String.valueOf(totalPoints)+" points");
	        		isStillOk=false;
	        		updateNewScore();
	        		typeOfGameOver=1;
	        		showGameOver();
	        		//AlertDialog alert = builder.create();
	        	    //alert.show();	        		
	        		return false;
	        	}
	        	if (myView.getCurrentColor()==0 && diff>maxDelay){
	        		//Log.e("De mau trang troi qua", "De mau trang troi qua");
	        		running=false;
	        		oldTime=System.currentTimeMillis();
	        		newTime=oldTime;
	        		myView.setGameOver(gameOver+"Your EQ scores are "+String.valueOf(totalPoints)+" points");
	        		myView.setLabelText(gameOver+"Your EQ scores are "+String.valueOf(totalPoints)+" points");	        		
	        		isStillOk=false;
	        		updateNewScore();
	        		typeOfGameOver=0;
	        		showGameOver();
	        		//AlertDialog alert = builder.create();
	        	    //alert.show();
	        		return false;
	        	}
	        	//if (myView.getCurrentColor()==1){
	        		//oldTime=System.currentTimeMillis();
	        		//newTime=oldTime;	        		
	        	//}
	        	oldTime=newTime;
	        	isStillOk=true;	        	
	        	myView.invalidate();
	        	totalPoints++;
	        	tv.setText("Score: "+String.valueOf(totalPoints));
	        	soundPool.play(soundIDTrue, 1.0f, 1.0f, 1, 0, 1.5f);
	        	//Log.e("Points",String.valueOf(totalPoints));
	            return false;
	        }
	    });
		//setReadyGame();
		//thread = new Thread(){
	        //@Override
	        //public void run() {
	        	//while(running){
		            //try {
		                //synchronized (this) {
		                    //wait(20);
		                    //runOnUiThread(new Runnable() {
		                        //@Override
		                        //public void run() {	                        	
		                        	//checkCondition();
		                        //}
		                    //});
	
		                //}
		            //} catch (InterruptedException e) {
		                //e.printStackTrace();
		            //}
	        	//}
	            //Intent DrawShapes1 = new Intent(getApplicationContext(),DrawShapes1.class);
	            //startActivity(DrawShapes1);
	        //};
	    //};
	    //thread.start();
		//setReadyGame();
		//while(countReadyGame>=1){}
		startGame();
		//restartGame();
		//showAd();
//		adView = new AdView(this);
//	    adView.setAdSize(AdSize.BANNER);	   
//	    adView.setAdUnitId(MY_AD_UNIT_ID);
//	    RelativeLayout rl = new RelativeLayout(this);
//	    RelativeLayout.LayoutParams lay = new RelativeLayout.LayoutParams(
//	        RelativeLayout.LayoutParams.FILL_PARENT, 
//	        RelativeLayout.LayoutParams.WRAP_CONTENT);
//	    lay.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);	    
//	    RelativeLayout layout = (RelativeLayout) findViewById(R.id.LinearLayout1);
//	    layout.addView(adView,lay);
//	    AdRequest adRequest = new AdRequest.Builder().build();
//	    adView.loadAd(adRequest);
	}
	private void playBeep() {
	    generator.startTone(TONE_TYPE, DOT_TIME);
	}
	public void startGame(){
		running=true;
		//if (thread.isAlive()){
			//thread.interrupt();
		//}	
		thread = new Thread(){
	        @Override
	        public void run() {
	        	while(running){
		            try {
		                synchronized (this) {
		                    wait(20);
		                    runOnUiThread(new Runnable() {
		                        @Override
		                        public void run() {	                        	
		                        	checkCondition();
		                        }
		                    });
	
		                }
		            } catch (InterruptedException e) {
		                e.printStackTrace();
		            }
	        	}
	          
	        };
	    };	    
	    thread.start();
	} 
	public void checkCondition(){
		if (!running) return;
		if (myView.getCurrentColor()==0){
			oldTime=myView.getOldTime();
			if (oldTime==0) oldTime=System.currentTimeMillis();
    		newTime=System.currentTimeMillis();
        	long diff=(newTime-oldTime);
        	if (diff>maxDelay){
        		//Log.e("checkCondition mau trang, cham cham", "checkCondition mau trang, cham cham");
        		running=false;
        		oldTime=System.currentTimeMillis();
        		newTime=oldTime;
        		myView.setGameOver(gameOver+"Your EQ scores are "+String.valueOf(totalPoints)+" points");
        		myView.setLabelText(gameOver+"Your EQ scores are "+String.valueOf(totalPoints)+" points");
        		isStillOk=false;
        		updateNewScore();
        		typeOfGameOver=0;
        		showGameOver();
        		//AlertDialog alert = builder.create();
        	    //alert.show();
        		return;
        	}
    	}
    	if (myView.getCurrentColor()==1){
    		//Log.e("checkCondition mau do", "checkCondition mau do");
    		isStillOk=false;
    		//oldTime=System.currentTimeMillis();
    		//newTime=oldTime;
    	}
    	oldTime=myView.getOldTime();
    	newTime=System.currentTimeMillis();
    	long diff=(newTime-oldTime);
        if (!isStillOk && diff>=maxDelay) myView.invalidate();
	
	}
	public void setReadyGame(){
		//if (thread.isAlive()){
			//thread.interrupt();
		//}	
    	thread = new Thread(){
	        @Override
	        public void run() {
	        	countReadyGame=3;
	        	myView.setIsReadyGame(true);
	        	while(countReadyGame>=1){
		            try {
		                synchronized (this) {
		                    wait(1000);
		                    runOnUiThread(new Runnable() {
		                        @Override
		                        public void run() {	                        	
		                        	myView.setCountReadyGame(countReadyGame);
		                        	myView.invalidate();
		                        }
		                    });
	
		                }
		            } catch (InterruptedException e) {
		                e.printStackTrace();
		            }
		            countReadyGame=countReadyGame-1;
	        	}
	        	myView.setIsReadyGame(false);
	        };
	    };
	    thread.start();
	}
	public void restartGame(){		
		running=true;
		if (thread.isAlive()){
			thread.interrupt();
		}	
    	thread = new Thread(){
	        @Override
	        public void run() {	        	
	        	while(running){
		            try {
		                synchronized (this) {
		                    wait(20);
		                    runOnUiThread(new Runnable() {
		                        @Override
		                        public void run() {	                        	
		                        	checkCondition();
		                        }
		                    });
	
		                }
		            } catch (InterruptedException e) {
		                e.printStackTrace();
		            }
	        	}
	            //Intent DrawShapes1 = new Intent(getApplicationContext(),DrawShapes1.class);
	            //startActivity(DrawShapes1);
	        };
	    };
	    tv.setText(startGameGuide);
	    myView.setRestartGame();
	    myView.setLabelText("Touch");
		totalPoints=0;
		oldTime=System.currentTimeMillis();
		newTime=oldTime;
	    thread.start();
	}
	public void saveHightScore(){
		SharedPreferences sharedPreferences = this.getSharedPreferences(packageName, Context.MODE_PRIVATE);
	    SharedPreferences.Editor editor = sharedPreferences.edit();
	    editor.putInt("Score", newHighScore);
	    editor.commit();
	}
	public int getHightSorce(){
		SharedPreferences sharedPreferences = this.getSharedPreferences(packageName, Context.MODE_PRIVATE);
	    int score = sharedPreferences.getInt("Score", 0);
	    return score;
	}
	public void updateNewScore(){
		if (totalPoints>newHighScore){
			newHighScore=totalPoints;
			tv.setText("Scores: "+String.valueOf(totalPoints)+", High scores: "+String.valueOf(totalPoints));
			saveHightScore();
		}else{
			tv.setText("Score: "+String.valueOf(totalPoints)+", High score: "+String.valueOf(newHighScore));
		}
	}
	public void showGameOver(){
			soundPool.play(soundIDOver, 1.0f, 1.0f, 1, 0, 1.5f);
			//playBeep();
		    alertDialogBuilder = new AlertDialog.Builder(this);
			// set title
			alertDialogBuilder.setTitle("Game over! "+gameOverAlert[typeOfGameOver]);
			// set dialog message
			alertDialogBuilder
				.setMessage("Score: "+String.valueOf(totalPoints)+", High score: "+String.valueOf(newHighScore)+".")
				.setCancelable(false)
				.setPositiveButton("Play again.",new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog,int id) {
						// if this button is clicked, close
						// current activity
						alertDialog.hide();						
		        		restartGame();
					}
				  })
				  .setNeutralButton("Share your high score!",new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog,int id) {
						Log.e("share", "1");
						Bitmap screenshot = Bitmap.createBitmap(_rootView.getWidth(), _rootView.getHeight(), Bitmap.Config.RGB_565);
						_rootView.draw(new Canvas(screenshot));
						Log.e("share", "2");
						String path = storeImage(screenshot);// Images.Media.insertImage(getContentResolver(), screenshot, "title", null);
						//path=savePic(Mode.SCREEN,Mode.SCREEN,path);
						Log.e("storeImage",path);
						Uri screenshotUri = Uri.fromFile(currentFile);
						Log.e("share", "3");
						final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
						//emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						emailIntent.setType("image/*");
						emailIntent.putExtra(Intent.EXTRA_STREAM, screenshotUri);
						emailIntent.setType("text/plain");
						emailIntent.putExtra(Intent.EXTRA_TEXT, "My EQ scores are "+String.valueOf(totalPoints)+" points, Test with this game: https://play.google.com/store/apps/details?id=com.huynv.redblue");
						
        				
						Log.e("share", "4");
						startActivity(Intent.createChooser(emailIntent, "Share your excellent high score!"));
						Log.e("share", "5");
						myView.setGameOver(gameOver+"Your EQ scores are "+String.valueOf(totalPoints)+" points");
		        		myView.setLabelText(gameOver+"Your EQ scores are "+String.valueOf(totalPoints)+" points");
		        		
					}
				  })
				.setNegativeButton("Exit",new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog,int id) {
						// if this button is clicked, close
						// current activity
						PlayGame.this.finish();
						//MainActivity.this.finish();
				    	System.exit(0);						
					}
				  });
				// create alert dialog
				alertDialog = alertDialogBuilder.create();
				// show it
				alertDialog.show();
			
	}
	public void showAd(){
		    adView = new AdView(context);
		    adView.setAdSize(AdSize.BANNER);	   
		    adView.setAdUnitId(MY_AD_UNIT_ID);
		    RelativeLayout rl = new RelativeLayout(this);
		    RelativeLayout.LayoutParams lay = new RelativeLayout.LayoutParams(
		        RelativeLayout.LayoutParams.FILL_PARENT, 
		        RelativeLayout.LayoutParams.WRAP_CONTENT);
		    lay.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);	    
		    RelativeLayout layout = (RelativeLayout) findViewById(R.id.LinearLayout1);
		    layout.addView(adView,lay);
		    AdRequest adRequest = new AdRequest.Builder().build();
		    adView.loadAd(adRequest);
	    //myView.addView(adView);
	}
	 private String savePic(PorterDuff.Mode modeOut,PorterDuff.Mode modeMain,String path)
	   {
		   /* Get the size of the ImageView */
			int targetW = 300;// 300;//mainImage.getWidth();
			int targetH = 200;//200;//mainImage.getHeight();

			/* Get the size of the image */
			BitmapFactory.Options bmOptions = new BitmapFactory.Options();
			bmOptions.inJustDecodeBounds = true;
			BitmapFactory.decodeFile(path, bmOptions);
			int photoW = bmOptions.outWidth;
			int photoH = bmOptions.outHeight;
			
			/* Figure out which way needs to be reduced less */
			int scaleFactor = 1;
			if ((targetW > 0) && (targetH > 0)) {
				scaleFactor = Math.min(photoW/targetW, photoH/targetH)+1;	
			}
			//Log.e("setPic", "scaleFactor="+String.valueOf(scaleFactor)+",photoW="+String.valueOf(photoW)+",targetW="+String.valueOf(targetW)); 
			/* Set bitmap options to scale the image decode target */
			bmOptions.inJustDecodeBounds = false;
			bmOptions.inSampleSize = scaleFactor;//scaleFactor;
			bmOptions.inPurgeable = true;
			//bmOptions.inScreenDensity=true;
			/* Decode the JPEG file into a Bitmap */
			Bitmap bitmap = BitmapFactory.decodeFile(path, bmOptions);
			//Bitmap bitmap2 = BitmapFactory.decodeFile(path, bmOptions);
			//bitmapBitmap result;
			bitmap = Bitmap.createScaledBitmap(bitmap, 300, 200, false);
			//Log.e("setPic", "ok");
			//mImageBitmap = bitmap;
          //Bitmap bp =(Bitmap) extras.get("data");// setPic();
			//result=MapImage(bitmap,bitmap2,modeOut,modeMain);
			
			return storeImage(bitmap);
			//mainImage.setImageBitmap(bitmap);
			//mainImage.setImageBitmap(result);
			//output=result;
  		//Log.e("setPic", "ok1"); 
			//return result;
	   }
	private String storeImage(Bitmap image) {
		String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmmss").format(new Date());
        File pictureFile = getOutputMediaFile(timeStamp);
        Log.e("storeImage", "ok1");
        if (pictureFile == null) {
        	Log.e("storeImage", "noooo");
            //Log.d(TAG,
                    //"Error creating media file, check storage permissions: ");// e.getMessage());
            return "";
        } 
        try {
            FileOutputStream fos = new FileOutputStream(pictureFile);
            image.compress(Bitmap.CompressFormat.PNG, 90, fos);
            fos.close();
            Log.e("storeImage", "ok2");
        } catch (Exception e) {
            //Log.d(TAG, "File not found: " + e.getMessage());
        }  
        currentFile=pictureFile;
        return pictureFile.getAbsolutePath();
    }
    private  File getOutputMediaFile(String fileName){
        // To be safe, you should check that the SDCard is mounted
        // using Environment.getExternalStorageState() before doing this. 
        File mediaStorageDir = new File(Environment.getExternalStorageDirectory()
                + "/Pictures/RedBlueGame/"); 

        // This location works best if you want the created images to be shared
        // between applications and persist after your app has been uninstalled.

        // Create the storage directory if it does not exist
        if (! mediaStorageDir.exists()){
            if (! mediaStorageDir.mkdirs()){
                return null;
            }
        } 
        // Create a media file name
        //String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date());
        File mediaFile;
            String mImageName=fileName+".png";
            mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);  
        return mediaFile;
    }
	//private Paint circlePaint;
	//public void drawLogo() {		
		//get half of the width and height as we are working with a circle
		//Log.e("onDraw", "ok1");
		//Canvas canvas=new Canvas();
		
		//get the radius as half of the width or height, whichever is smaller
		//subtract ten so that it has some space around it
		//int radius = 10;
		//set drawing properties
		//circlePaint.setStyle(Style.FILL);
		//circlePaint.setAntiAlias(true);
		//set the paint color using the circle color specified
		//circlePaint.setColor(Color.WHITE);		
		//Paint circleColor =new Paint();
		//circleColor.setColor(Color.WHITE);
		//canvas.drawCircle(20, 20, radius, circleColor);
		//circleColor.setColor(Color.RED);
		//canvas.drawCircle(30, 30, radius, circleColor);
	//}
	@Override
	  public void onResume() {
	    super.onResume();	    
	  }

	  @Override
	  public void onPause() {	    
	    super.onPause();
	  }

	  /** Called before the activity is destroyed. */
	  @Override
	  public void onDestroy() {
	    // Destroy the AdView.
	    if (adView != null) {
	      adView.destroy();
	    }
	    super.onDestroy();
	  }
}
